$(function() {
	// wait for the DOM to be loaded
	$(document)
			.ready(
					function() {
						updateLoginState();
						$('.typeahead').typeahead();
						$('.dropdown-toggle').dropdown();
						var options = {
							success : function(responseXML) {
								var res = $('result', responseXML).text();
								if (res == 'success') {
									$('#add-success-info').html('添加好友成功！');
									$('#add-success-info').css('display',
											'');
									$('#add-failed-info').html('');
									$('#add-failed-info')
											.css('display', 'none');
								} else {
									$('#add-failed-info').html('添加好友失败！');
									$('#add-failed-info').css('display',
											'');
									$('#add-success-info').html('');
									$('#add-success-info').css('display',
											'none');
								}
								$('#info-area-dialog').dialog('open');

							},
							dataType : 'xml',
							clearForm : true,
						};
						$('#addfriendForm').submit(function() {
							$(this).ajaxSubmit(options);
							return false;
						});
						var options2 = {
							success : function(responseXML) {
								var res = $('result', responseXML).text();
								if (res == 'success') {
									$('#add-success-info').html('添加分组成功！');
									$('#add-success-info').css('display',
											'');
									$('#add-failed-info').html('');
									$('#add-failed-info')
											.css('display', 'none');
								} else {
									$('#add-failed-info').html('添加分组失败！');
									$('#add-failed-info').css('display',
											'');
									$('#add-success-info').html('');
									$('#add-success-info').css('display',
											'none');
								}
								$('#info-area-dialog').dialog('open');

							},
							dataType : 'xml',
							clearForm : true,
						};
						$('#addGroupForm').submit(function() {
							$(this).ajaxSubmit(options2);
							return false;
						});
						var options3 = {
							success : function(responseXML) {
								var res = $('result', responseXML).text();
								if (res == 'success') {
									$('#add-success-info').html('更新成功！');
									$('#add-success-info').css('display',
											'');
									$('#add-failed-info').html('');
									$('#add-failed-info')
											.css('display', 'none');
								} else {
									$('#add-failed-info').html('更新失败！');
									$('#add-failed-info').css('display',
											'');
									$('#add-success-info').html('');
									$('#add-success-info').css('display',
											'none');
								}
								$('#info-area-dialog').dialog('open');

							},
							clearForm : true,
						};

						$('#saveFriendInfoForm').submit(function() {
							$(this).ajaxSubmit(options3);
							$('#view-user-info-dialog').dialog('close');
							return false;
						});
						var options4 = {
								success : function(responseXML) {
									var res = $('result', responseXML).text();
									if (res == 'success') {
										$('#add-success-info').html('信息保存成功！');
										$('#add-success-info').css('display',
												'');
										$('#add-failed-info').html('');
										$('#add-failed-info')
												.css('display', 'none');
									} else {
										$('#add-failed-info').html('信息保存失败！');
										$('#add-failed-info').css('display',
												'');
										$('#add-success-info').html('');
										$('#add-success-info').css('display',
												'none');
									}
									$('#info-area-dialog').dialog('open');

								},
							clearForm : false,
						};

						$('#saveProfileForm').submit(function() {
							$(this).ajaxSubmit(options4);
							$('#edit-profile-dialog').dialog('close');
							return false;
						});

						var options5 = {
							success : function(responseXML) {
								var res = $('result', responseXML).text();
								if (res == 'success') {
									$('#add-success-info').html('修改密码成功！');
									$('#add-success-info').css('display',
											'');
									$('#add-failed-info').html('');
									$('#add-failed-info')
											.css('display', 'none');
								} else {
									$('#add-failed-info').html('修改密码失败！');
									$('#add-failed-info').css('display',
											'');
									$('#add-success-info').html('');
									$('#add-success-info').css('display',
											'none');
								}
								$('#info-area-dialog').dialog('open');
							},
							clearForm : true,
						};

						$('#savePasswordForm').submit(function() {
							$(this).ajaxSubmit(options5);
							$('#change-pasword-dialog').dialog('close');
							return false;
						});

						var bar = $('.bar');
						var percent = $('.percent');
						$('#uploadFileForm')
								.ajaxForm(
										{
											beforeSend : function() {
												var percentVal = '0%';
												bar.width(percentVal);
												percent.html(percentVal);
											},
											uploadProgress : function(event,
													position, total,
													percentComplete) {
												var percentVal = percentComplete
														+ '%';
												bar.width(percentVal);
												percent.html(percentVal);
											},
											complete : function(xhr) {
												$('#upload-file-success-info')
														.css('display',
																'');
												var uid = $('#uploadUserId')
														.val();
												$('#chat_dialog_' + uid)
														.find(".chat_content")
														.append(
																'<p style="color: #777">您已成功向对方发送文件<p>');

											}
										});

					});

	$("input:submit, button", ".send_message_area, .add_friend_area").button();
	// Accordion
	$("#accordion").accordion({
		header : "h3",
		autoHeight : false
	});
	$('#add_friend_dialog').dialog({
		autoOpen : false,
		width : 498,
		height : 390,
		resizable : false,
		show : "fade"
	});
	$('#add_group_dialog').dialog({
		autoOpen : false,
		width : 350,
		height : 250,
		resizable : false,
		show : "fade"
	});

	$('#upload-file-dialog').dialog({
		autoOpen : false,
		width : 400,
		height : 250,
		resizable : false,
		modal : true,
		show : "fade"
	});

	$('#view-user-info-dialog').dialog({
		autoOpen : false,
		width : 550,
		height : 450,
		resizable : false,
		title : '查看用户信息',
		show : "fade"
	});

	$('#edit-profile-dialog').dialog({
		autoOpen : false,
		width : 550,
		height : 410,
		resizable : false,
		title : '编辑个人资料',
		show : "fade"
	});

	$('#change-pasword-dialog').dialog({
		autoOpen : false,
		width : 550,
		height : 400,
		resizable : false,
		title : '更改密码',
		show : "fade"
	});

	$('#info-area-dialog').dialog({
		autoOpen : false,
		width : 300,
		height : 130,
		resizable : false,
		title : '提示信息',
		show : "fade",
		modal : true
	});

	$('#panel').draggable();
	$('a.uName')
			.click(
					function() {
						chatUserId = $(this).parent().find('.uid').html();
						if ($('#chat_dialog_' + chatUserId).length <= 0) {
							$('#dialog-area')
									.append(
											'<div class="single_chat_dialog" id="chat_dialog_'
													+ chatUserId
													+ '">\n'
													+ '<div class="chat_content"></div> \n'
													+ '<div> \n'
													+ '<form id="chat_form_'
													+ chatUserId
													+ '" action="sendmessage" method="post" class="sendmessageForm" \n'
													+ 'class="send_message_area"> \n'
													+ '<input type="hidden" class="toUser" name="toUser" value="'
													+ chatUserId
													+ '">'
													+ '<div> \n'
													+ '<textarea name="message" class="input_square"></textarea> \n'
													+ '</div> \n'
													+ '<div class="pull-right">'
													+ '<a class="uploadFileLink btn">上传文件 </a> \n'
													+ '<input type="submit" value="发送消息" \n'
													+ 'class=" btn btn-primary"></input> \n'
													+ '</div>' + '</form> \n'
													+ '</div> \n' + '</div> \n');
						}
						$('#chat_dialog_' + chatUserId).dialog({
							autoOpen : false,
							width : 420,
							height : 370,
							resizable : false
						});
						$('#chat_dialog_' + chatUserId).dialog(
								{
									title : "与 "
											+ $(this).parent().find('.uName')
													.html() + " 聊天中"
								});
						$('#chat_dialog_' + chatUserId).dialog('open');
						$('#chat_dialog_' + chatUserId)
								.find('.sendmessageForm').submit(
										ajaxSendMessage);

						$('.uploadFileLink').click(
								function() {
									var userId = $(this).parents(
											'.single_chat_dialog').find(
											'.toUser').attr('value');
									$('#uploadUserId').val(userId);
									$('.percent').html('未开始');
									$('.bar').width(0);
									$('#upload-file-success-info').css(
											'display', 'none');
									$('#upload-file-failed-info').css(
											'display', 'none');
									$('#upload-file-dialog').dialog('open');
								});
						return false;
					});

	$('#add_friend_link').click(function() {

		$('#add_friend_dialog').dialog('open');
	});
	$('#add_group_link').click(function() {
		$('#add_group_dialog').dialog('open');
	});
	$('#view-user-close').click(function() {
		$('#view-user-info-dialog').dialog('close');
	});
	$('#editProfileLink').click(function() {
		$('#edit-profile-dialog').dialog('open');
	});
	$('#changePasswordLink').click(function() {
		$('#change-pasword-dialog').dialog('open');
	});
	$('#edit-profile-close').click(function() {
		$('#edit-profile-dialog').dialog('close');
	});
	$('#change-password-close').click(function() {
		$('#change-pasword-dialog').dialog('close');
	});
	$('#info-area-close').click(function() {
		$('#info-area-dialog').dialog('close');
	});

	$('.friend-avatar').click(function() {
		var userId = $(this).parent().find('.uid').text();
		var groupId = $(this).parents('.group-entity').find('.groupId').text();
		$('#viewGroupId').val(groupId);
		$('#viewUserId').val(userId);
		$('#originalGroupId').val(groupId);
		$('#view-user-info-dialog').dialog('open');
		$.get("getUserInfo", {
			'userId' : userId,
			'viewGroupId' : groupId
		}, function(result) {
			var userName = $('userName', result).text();
			var nickName = $('nickName', result).text();
			var email = $('email', result).text();
			var avatarLink = $('avatar', result).text();
			$('#viewFriendName').attr('value', userName);
			$('#viewNickName').attr('value', nickName);
			$('#viewGroupId').attr('headerKey', groupId);
			$('#viewEmail').attr('value', email);
			$('#viewUserAvatar').attr('src', avatarLink);
		});
	});

	$('#delFriendship').click(
			function() {
				var uid = $(this).parents('#saveFriendInfoForm').find(
						'#viewUserId').attr('value');
				var groupId = $(this).parents('#saveFriendInfoForm').find(
						'#originalGroupId').attr('value');
				$.get("delFriendship", {
					'uid' : uid,
					'groupId' : groupId
				});
			});

});

function getUnreadMessage() {
	$(document).ready(function() {
		$.ajax({
			type : "GET",
			url : "receivemessage",
			dataType : "xml",
			success : dealWithUnreadMessage
		});
	});
}

setInterval('getUnreadMessage()', 1000);

function dealWithUnreadMessage(responseXML, statusText, xhr, $form) {
	$('message', responseXML)
			.each(
					function() {
						var senderId = $(this).find('senderId').text();
						var senderName = $(this).find('senderName').text();
						var content = $(this).find('content').text();
						re = new RegExp("{", "g");
						content = content.replace(re, "<");
						re = new RegExp("}", "g");
						content = content.replace(re, ">");
						var nowTime = new Date();
						if ($('#chat_dialog_' + senderId).length <= 0) {
							$('#dialog-area')
									.append(
											'<div class="single_chat_dialog" id="chat_dialog_'
													+ senderId
													+ '">\n'
													+ '<div class="chat_content"></div> \n'
													+ '<div> \n'
													+ '<form id="chat_form_'
													+ senderId
													+ '" action="sendmessage" method="post" class="sendmessageForm" \n'
													+ 'class="send_message_area"> \n'
													+ '<input type="hidden" class="toUser" name="toUser" value="'
													+ senderId
													+ '">'
													+ '<div> \n'
													+ '<textarea name="message" class="input_square"></textarea> \n'
													+ '</div> \n'
													+ '<div class="pull-right">'
													+ '<a class="uploadFileLink btn">上传文件 </a> \n'
													+ '<input type="submit" value="发送消息" \n'
													+ 'class=" btn btn-primary"></input> \n'
													+ '</div>' + '</form> \n'
													+ '</div> \n' + '</div> \n');

							$('#chat_dialog_' + senderId).dialog({
								autoOpen : false,
								width : 420,
								height : 370,
								resizable : false
							});
							$('#chat_dialog_' + senderId).dialog({
								title : "与 " + senderName + " 聊天中"
							});
							$('#chat_dialog_' + senderId).dialog('open');
							$('#chat_dialog_' + senderId).find(
									'.sendmessageForm').submit(ajaxSendMessage);
						}
						$('#chat_dialog_' + senderId)
								.find(".chat_content")
								.append(
										'<p>'
												+ senderName
												+ '&nbsp;发表于'
												+ '<a style=\'color: red;\'>&nbsp;&nbsp;'
												+ nowTime.toLocaleTimeString()
												+ '</a>' + '</p>' + '<p>'
												+ content + '</p>');
					});
}

function ajaxSendMessage() {
	var options = {
		target : $(".chat_content"),
		dataType : 'xml',
		clearForm : true,
		beforeSubmit : function(formData) {
			// var queryString = $.param(formData);
			// alert(queryString);
			var nowTime = new Date();
			if (formData[1].value == '')
				return false;
			$('#chat_dialog_' + formData[0].value).find(".chat_content")
					.append(
							'<p>' + $('#statue-user-name').text() + '&nbsp;发表于'
									+ '<a style=\'color: red;\'>&nbsp;&nbsp;'
									+ nowTime.toLocaleTimeString() + '</a>'
									+ '</p>' + '<p>' + formData[1].value
									+ '</p>');
			return true;
		}
	};
	$(this).ajaxSubmit(options);
	return false;
}

function updateLoginState() {
	$.get("updateLoginState", function(result) {
		$('state', result).each(function() {
			var userId = $(this).find('userId').text();
			var state = $(this).find('userState').text();
			if (state == 'OFF_LINE') {
				$('#user_avatar_' + userId).addClass('avatar-offLine');
			} else {
				$('#user_avatar_' + userId).removeClass('avatar-offLine');
			}

		});
	});
}

setInterval('updateLoginState()', 10000);
